package xu.ye.view;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import xu.ye.bean.ContactBean;
import xu.ye.bean.GroupBean;
import xu.ye.uitl.BaseIntentUtil;
import xu.ye.uitl.Cn2Spell;
import xu.ye.uitl.ContactComparetor;
import xu.ye.view.adapter.ContactHomeAdapter;
import xu.ye.view.adapter.MenuListAdapter;
import xu.ye.view.other.SizeCallBackForMenu;
import xu.ye.view.sms.MessageBoxList;
import xu.ye.view.ui.MenuHorizontalScrollView;
import xu.ye.view.ui.QuickAlphabeticBar;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.AsyncQueryHandler;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.GroupMembership;
import android.provider.ContactsContract.Groups;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.agent.crm.config.AppConfig;
import com.agent.crm.db.DBInitScript;
import com.agent.crm.db.DatabaseManager;
import com.agent.crm.util.CnToSpell;
import com.agent.crm.util.DateUtils;
import com.agent.crm.view.R;
import com.google.gson.Gson;
import com.pwp.activity.ScheduleView;

public class HomeContactActivity extends Activity {

	private MenuHorizontalScrollView scrollView;
	private ListView menuList;
	private View acbuwaPage;
	private Button menuBtn;
	private MenuListAdapter menuListAdapter;
	private View[] children;
	private LayoutInflater inflater;


	private ContactHomeAdapter adapter;
	private ListView personList;
	private List<ContactBean> list;
	private AsyncQueryHandler asyncQuery;
	private QuickAlphabeticBar alpha;
	private Button addContactBtn;
	
	private ProgressDialog pdDialog; 

	private Map<Integer, ContactBean> contactIdMap = null;
	
	private DatabaseManager manager = null;
	
	public static final int CONTACT_ADD_EDIT_REQUST_CODE = 40;
	public static final int TASK_ADD_REQUEST_CODE = 4;
	
	
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		inflater = LayoutInflater.from(this);
		setContentView(inflater.inflate(R.layout.menu_scroll_view, null));



		scrollView = (MenuHorizontalScrollView)findViewById(R.id.mScrollView);
		menuListAdapter = new MenuListAdapter(this, queryGroup());
		menuList = (ListView)findViewById(R.id.menuList);
		menuList.setAdapter(menuListAdapter);


		acbuwaPage = inflater.inflate(R.layout.home_contact_page, null);
		menuBtn = (Button)this.acbuwaPage.findViewById(R.id.menuBtn);

		personList = (ListView)this.acbuwaPage.findViewById(R.id.acbuwa_list);

		alpha = (QuickAlphabeticBar)this.acbuwaPage.findViewById(R.id.fast_scroller);
		asyncQuery = new MyAsyncQueryHandler(getContentResolver());
		manager = new DatabaseManager(this);
		//manager.deleteDatabase(this);

		menuBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				scrollView.clickMenuBtn(HomeContactActivity.this);
			}
		});

		View leftView = new View(this);
		leftView.setBackgroundColor(Color.TRANSPARENT);
		children = new View[]{leftView, acbuwaPage};
		scrollView.initViews(children, new SizeCallBackForMenu(this.menuBtn), this.menuList);
		scrollView.setMenuBtn(this.menuBtn);
		((Button) findViewById(R.id.back)).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		addContactBtn = (Button) findViewById(R.id.addContactBtn);
		addContactBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
			    Intent intent =new Intent();
			    intent.setClass(HomeContactActivity.this, AddNewActivity.class);
	            startActivityForResult(intent, CONTACT_ADD_EDIT_REQUST_CODE);
			}
		});
		pdDialog =new ProgressDialog(this);
		pdDialog.setMessage("正在初始化联系人");
		pdDialog.show();
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				while(AppConfig.loadingFromMobileContacts){
					try {
						Thread.sleep(3000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				handler.sendEmptyMessage(0);
			}
		}).start();
		
	}
	
	Handler handler =new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			init();
			startReceiver1();
		}
		
	};
	
	public static String[] projection = { 
            ContactsContract.CommonDataKinds.Phone._ID,
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
            ContactsContract.CommonDataKinds.Phone.DATA1,
            ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
            ContactsContract.CommonDataKinds.Phone.PHOTO_ID,
            ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY
    }; // 查询的列
	
	
	private void init(){
	   
	    SQLiteDatabase sqlLite = manager.getWritableDatabase();
	    list = new ArrayList<ContactBean>();
	    sqlLite.beginTransaction();
	    
	    Cursor cursor = sqlLite.query(DBInitScript.Table_ContactsInfo, new String[]{"sys_contactid", "name", "mobile_phone", "sort_key", "lookup_key", "photoid", "is_attention", "contacts_id"}, null, null, null, null, null, null);
	    int count = cursor.getCount();
	    if(count == 0){
	        refreshContacts();
        }
	    else{
	        list = new ArrayList<ContactBean>();
	        for(int i = 0; i < count; i++){
	            cursor.moveToPosition(i);
	            int contactId = cursor.getInt(0);
	            String name = cursor.getString(1);
	            String mobilePhone = cursor.getString(2);
	            String sortKey = cursor.getString(3);
	            String lookupKey = cursor.getString(4);
	            Long photoId = cursor.getLong(5);
	            int isAttention = cursor.getInt(6);
	            int customContactsId = cursor.getInt(7);
	            
	            ContactBean bean = new ContactBean();
	            bean.setContactId(contactId);
	            bean.setDisplayName(name);
	            bean.setSortKey(sortKey);
	            bean.setPhoneNum(mobilePhone);
	            bean.setLookUpKey(lookupKey);
	            bean.setPhotoId(photoId);
	            bean.setIsAttention(isAttention);
	            bean.setCustomContactsId(customContactsId);
	            list.add(bean);
	        }
	        if(list.size() > 0){
	            ContactComparetor comparetor = new ContactComparetor();
                Collections.sort(list, comparetor);
	            setAdapter(list);
	        }
	        
	    }
	    sqlLite.setTransactionSuccessful();
	    sqlLite.endTransaction();  
	    
	    
	    cursor.close();
        sqlLite.close(); 
        if(null!=pdDialog&&pdDialog.isShowing()){
        	pdDialog.dismiss();
        }
		
	}

	private void refreshContacts(){
	    asyncQuery.startQuery(0, null, ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, null, null,
                "display_name COLLATE LOCALIZED asc"); // 按照sort_key升序查询
	}
	
	
	
	
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if(keyCode == KeyEvent.KEYCODE_BACK){
			if(MenuHorizontalScrollView.menuOut == true)
				this.scrollView.clickMenuBtn(HomeContactActivity.this);
			else
				this.finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}	

	/**
	 * 数据库异步查询类AsyncQueryHandler
	 * 
	 * @author administrator
	 * 
	 */
	@SuppressLint("UseSparseArrays")
    private class MyAsyncQueryHandler extends AsyncQueryHandler {

		public MyAsyncQueryHandler(ContentResolver cr) {
			super(cr);
		}

		/**
		 * 查询结束的回调函数
		 */
		@Override
		protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
		    SQLiteDatabase sqlLite = manager.getWritableDatabase();
		    sqlLite.beginTransaction();
		    sqlLite.delete(DBInitScript.Table_ContactsInfo, null, null);
		    
		    ContentValues content = new ContentValues();
			if (cursor != null && cursor.getCount() > 0) {
				
				contactIdMap = new HashMap<Integer, ContactBean>();
				
				list = new ArrayList<ContactBean>();
				cursor.moveToFirst();
				for (int i = 0; i < cursor.getCount(); i++) {
					cursor.moveToPosition(i);
					String name = cursor.getString(1);
					String number = cursor.getString(2);
					String sortKey = CnToSpell.getFirstSpell(name);
					int contactId = cursor.getInt(3);
					Long photoId = cursor.getLong(4);
					String lookUpKey = cursor.getString(5);
					content.put("name", name);
					content.put("mobile_phone", number);
					content.put("sort_key", sortKey);
					content.put("lookup_key", lookUpKey);
					content.put("photoid", photoId);
					content.put("sys_contactid", contactId);
					content.put("is_attention", 0);
					sqlLite.insert(DBInitScript.Table_ContactsInfo, null, content);
					
					if (contactIdMap.containsKey(contactId)) {
						
					}else{
						
						ContactBean cb = new ContactBean();
						cb.setDisplayName(name);
//					if (number.startsWith("+86")) {// 去除多余的中国地区号码标志，对这个程序没有影响。
//						cb.setPhoneNum(number.substring(3));
//					} else {
						cb.setPhoneNum(number);
//					}
						cb.setSortKey(sortKey);
						cb.setContactId(contactId);
						cb.setPhotoId(photoId);
						cb.setLookUpKey(lookUpKey);
						cb.setIsAttention(0);
						list.add(cb);
						//sqlLite.insert(sortKey, lookUpKey, null);
						contactIdMap.put(contactId, cb);
						
					}
				}
				if (list.size() > 0) {
				    ContactComparetor comparetor = new ContactComparetor();
				    Collections.sort(list, comparetor);
					setAdapter(list);
				}
			}
			sqlLite.setTransactionSuccessful();
			sqlLite.endTransaction();
			sqlLite.close();
		}

	}


	private void setAdapter(List<ContactBean> list) {
		adapter = new ContactHomeAdapter(this, list, alpha);
		personList.setAdapter(adapter);
		alpha.init(HomeContactActivity.this);
		alpha.setListView(personList);
		alpha.setVisibility(View.VISIBLE);
		personList.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				ContactBean cb = (ContactBean) adapter.getItem(position);
				int isAttention = cb.getIsAttention();
				if(isAttention == 0){
				    lianxiren1[3] = "添加关注";
				}
				else{
				    lianxiren1[3] = "取消关注";
				}
				showContactDialog(lianxiren1, cb, position);
			}
		});
	}


	private String[] lianxiren1 = new String[] { "拨打电话", "发送短信", "查看详细", "添加关注", "添加任务", "删除" };

	//群组联系人弹出页
	private void showContactDialog(final String[] arg ,final ContactBean cb, final int position){
		new AlertDialog.Builder(this).setTitle(cb.getDisplayName()).setItems(arg,
				new DialogInterface.OnClickListener(){
			public void onClick(DialogInterface dialog, int which){

				Uri uri = null;

				switch(which){

				case 0://打电话
					String toPhone = cb.getPhoneNum();
					uri = Uri.parse("tel:" + toPhone);
					Intent it = new Intent(Intent.ACTION_CALL, uri);
					startActivity(it);
					break;

				case 1://发短息
				    String phoneNum = cb.getPhoneNum();
				    if(TextUtils.isEmpty(phoneNum)){
                        Toast.makeText(getApplicationContext(), "手机号码为空", Toast.LENGTH_LONG).show();
                        return;
                    }
					String threadId = getSMSThreadId(phoneNum);
					Map<String, String> map = new HashMap<String, String>();
					map.put("phoneNumber", phoneNum);
					map.put("threadId", threadId);
					BaseIntentUtil.intentSysDefault(HomeContactActivity.this, MessageBoxList.class, map);
					break;

				case 2:// 查看详细       修改联系人资料
                    Intent intent2 = new Intent();
				    SQLiteDatabase sqlAction = manager.getWritableDatabase();
				    Cursor cursor = sqlAction.query(DBInitScript.Table_ContactsInfo, null, "contacts_id=" + cb.getCustomContactsId(), null, null, null, null, null);
				    if(cursor == null || cursor.getCount() != 1){
				        break;
				    }
				    //设置为编辑操作
				    intent2.putExtra("edit", true);
				    cursor.moveToFirst();
                    int index = -1;
                    index = cursor.getColumnIndex("contacts_id");
                    intent2.putExtra("contacts_id", cursor.getInt(index));
                    
                    index = cursor.getColumnIndex("sys_contactid");
                    intent2.putExtra("sys_contactid", cursor.getInt(index));
                    
                    index = cursor.getColumnIndex("name");
                    intent2.putExtra("name", cursor.getString(index));
                    
//                    index = cursor.getColumnIndex("age");
//                    intent2.putExtra("age", cursor.getInt(index));
                    
                    index = cursor.getColumnIndex("job");
                    intent2.putExtra("job", cursor.getString(index));
                    
                    index = cursor.getColumnIndex("address");
                    intent2.putExtra("address", cursor.getString(index));
                    
                    index = cursor.getColumnIndex("email");
                    intent2.putExtra("email", cursor.getString(index));
                    
                    index = cursor.getColumnIndex("sex");
                    intent2.putExtra("sex", cursor.getString(index));
                    
                    index = cursor.getColumnIndex("favious");
                    intent2.putExtra("favious", cursor.getString(index));
                    
                    index = cursor.getColumnIndex("company");
                    intent2.putExtra("company", cursor.getString(index));
                    
                    index = cursor.getColumnIndex("remarks");
                    intent2.putExtra("remarks", cursor.getString(index));
                    
                    index = cursor.getColumnIndex("family_phone");
                    intent2.putExtra("family_phone", cursor.getString(index));
                    
                    index = cursor.getColumnIndex("office_phone");
                    intent2.putExtra("office_phone", cursor.getString(index));
                    
                    index = cursor.getColumnIndex("mobile_phone");
                    intent2.putExtra("mobile_phone", cursor.getString(index));
                    
                    index = cursor.getColumnIndex("birth_date");
                    intent2.putExtra("birth_date", cursor.getString(index));
                    
				    intent2.setClass(HomeContactActivity.this, AddNewActivity.class);
				    startActivityForResult(intent2, CONTACT_ADD_EDIT_REQUST_CODE);
				    cursor.close();
				    sqlAction.close();
					break;

				case 3:// 关注
				    attentContact(cb);
					break;
				case 4://添加任务
				    Intent intentAdd = new Intent();
				    Calendar c = Calendar.getInstance();
                    int year = c.get(Calendar.YEAR);
                    int month = c.get(Calendar.MONTH) + 1;
                    int day = c.get(Calendar.DAY_OF_MONTH);
                    String ch_dayOfWeek = DateUtils.getWeek(c.getTime());
                    ArrayList<String> scheduleDate = new ArrayList<String>();
                    scheduleDate.add(year + "");
                    scheduleDate.add(month + "");
                    scheduleDate.add(day + "");
                    scheduleDate.add(ch_dayOfWeek);
                    intentAdd.putStringArrayListExtra("scheduleDate", scheduleDate);
//	                SQLiteDatabase sqlAction2 = manager.getWritableDatabase();
//                    Cursor cursor2 = sqlAction2.query(DBInitScript.Table_ContactsInfo, null, "sys_contactid=" + cb.getContactId(), null, null, null, null, null);
//                    if(cursor2 == null || cursor2.getCount() != 1){
//                        break;
//                    }
//                    cursor2.moveToFirst();
//                    int indexAdd = cursor2.getColumnIndex("contacts_id");
                    intentAdd.putExtra("objectID", String.valueOf(cb.getCustomContactsId()));
//                    indexAdd = cursor2.getColumnIndex("name");
                    intentAdd.putExtra("objectName", cb.getDisplayName());
                    intentAdd.putExtra("operateType", "add");
                    intentAdd.putExtra("from", "HomeContactActivity");
                    intentAdd.putExtra("scheduleMode", "0");
	                intentAdd.setClass(HomeContactActivity.this, ScheduleView.class);
//	                startActivityForResult(intentAdd,0);
	                startActivityForResult(intentAdd, TASK_ADD_REQUEST_CODE);
//	                cursor2.close();
//	                sqlAction2.close();
				    break;
				case 5:// 删除

					showDelete(cb.getContactId(), position);
					break;
				}
			}
		}).show();
	}
	
	private void attentContact(ContactBean cb){
	    SQLiteDatabase database = manager.getWritableDatabase();
	    ContentValues values = new ContentValues();
	    if(cb.getIsAttention() == 1){
	        values.put("is_attention", 0);
	    }
	    else{
	        values.put("is_attention", 1);
	    }
	    int result = database.update(DBInitScript.Table_ContactsInfo, values, "sys_contactid=?", new String[]{cb.getContactId() + ""});
	    if(result == -1){
	        Toast.makeText(getApplicationContext(), "操作失败", Toast.LENGTH_LONG).show();
	    }
	    if(cb.getIsAttention() == 1){
	        Toast.makeText(getApplicationContext(), "取消关注", Toast.LENGTH_LONG).show();
	        cb.setIsAttention(0);
	    }
	    else {
	        Toast.makeText(getApplicationContext(), "关注成功", Toast.LENGTH_LONG).show();
	        cb.setIsAttention(1);
	    }
	    
	    database.close();
	}
	
	

	// 删除联系人方法
	private void showDelete(final int contactsID, final int position) {
		new AlertDialog.Builder(this).setIcon(R.drawable.ic_launcher).setTitle("是否删除此联系人")
		.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				//源码删除
				Uri deleteUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactsID);
				Uri lookupUri = ContactsContract.Contacts.getLookupUri(HomeContactActivity.this.getContentResolver(), deleteUri);
				SQLiteDatabase dataBase = manager.getWritableDatabase();
				dataBase.delete(DBInitScript.Table_ContactsInfo, "sys_contactid = " + contactsID, null);
				
				
				if(lookupUri != Uri.EMPTY){
					HomeContactActivity.this.getContentResolver().delete(deleteUri, null, null);
				}
				adapter.remove(position);
				adapter.notifyDataSetChanged();
				Toast.makeText(HomeContactActivity.this, "该联系人已经被删除.", Toast.LENGTH_SHORT).show();
			}
		})
		.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {

			}
		}).show();
	}




	/**
	 * 
	 *查询所有群组
	 *返回值List<ContactGroup>
	 */
	public List<GroupBean> queryGroup(){

		List<GroupBean> list=new ArrayList<GroupBean>();

		GroupBean cg_all=new GroupBean();
		cg_all.setId(0);
		cg_all.setName("全部");
		list.add(cg_all);

		Cursor cur = getContentResolver().query(Groups.CONTENT_URI, null, null, null, null); 
		for (cur.moveToFirst();!(cur.isAfterLast());cur.moveToNext()) {
			if(null!=cur.getString(cur.getColumnIndex(Groups.TITLE))&&(!"".equals(cur.getString(cur.getColumnIndex(Groups.TITLE))))){
				GroupBean cg=new GroupBean();
				cg.setId(cur.getInt(cur.getColumnIndex(Groups._ID)));
				cg.setName(cur.getString(cur.getColumnIndex(Groups.TITLE)));
				list.add(cg);
			}
		}   
		cur.close();
		return list;
	}









	private void queryGroupMember(GroupBean gb){

		String[] RAW_PROJECTION = new String[]{ContactsContract.Data.RAW_CONTACT_ID};  

		Cursor cur = getContentResolver().query(ContactsContract.Data.CONTENT_URI,RAW_PROJECTION,  
				ContactsContract.Data.MIMETYPE+" = '"+GroupMembership.CONTENT_ITEM_TYPE  
				+"' AND "+ContactsContract.Data.DATA1+"="+ gb.getId(),     
				null,  
				"data1 asc"); 

		StringBuilder inSelectionBff = new StringBuilder().append(ContactsContract.RawContacts._ID + " IN ( 0");
		while(cur.moveToNext()){
			inSelectionBff.append(',').append(cur.getLong(0));
		}
		cur.close();	
		inSelectionBff.append(')');

		Cursor contactIdCursor =  getContentResolver().query(ContactsContract.RawContacts.CONTENT_URI,  
				new String[] { ContactsContract.RawContacts.CONTACT_ID }, inSelectionBff.toString(), null, ContactsContract.Contacts.DISPLAY_NAME+"  COLLATE LOCALIZED asc "); 
		Map<Integer,Integer> map=new HashMap<Integer,Integer>();  
		while (contactIdCursor.moveToNext()) {  
			map.put(contactIdCursor.getInt(0), 1);  
		}  
		contactIdCursor.close(); 

		Set<Integer> set = map.keySet();
		Iterator<Integer> iter = set.iterator();
		List<ContactBean> list=new ArrayList<ContactBean>();
		while(iter.hasNext()){
			Integer key = iter.next();
			list.add(queryMemberOfGroup(key));
		}
		setAdapter(list);
	}

	private ContactBean queryMemberOfGroup(int id){

		ContactBean cb = null;

		Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id, null, null);
		if (cursor != null && cursor.getCount() > 0) {
			list = new ArrayList<ContactBean>();
			cursor.moveToFirst();
			for (int i = 0; i < cursor.getCount(); i++) {
				cursor.moveToPosition(i);
				String name = cursor.getString(1);
				String number = cursor.getString(2);
				String sortKey = cursor.getString(3);
				int contactId = cursor.getInt(4);
				Long photoId = cursor.getLong(5);
				String lookUpKey = cursor.getString(6);

				cb = new ContactBean();
				cb.setDisplayName(name);
//				if (number.startsWith("+86")) {// 去除多余的中国地区号码标志，对这个程序没有影响。
//					cb.setPhoneNum(number.substring(3));
//				} else {
					cb.setPhoneNum(number);
//				}
				cb.setSortKey(sortKey);
				cb.setContactId(contactId);
				cb.setPhotoId(photoId);
				cb.setLookUpKey(lookUpKey);
			}
		}
		cursor.close();
		return cb;
	}




	public static String[] SMS_COLUMNS = new String[]{  
		"thread_id"
	};
	private String getSMSThreadId(String adddress){
		Cursor cursor = null;  
		ContentResolver contentResolver = getContentResolver();  
		cursor = contentResolver.query(Uri.parse("content://sms"), SMS_COLUMNS, " address like '%" + adddress + "%' ", null, null);  
		String threadId = "";
		if (cursor == null || cursor.getCount() > 0){
			cursor.moveToFirst();
			threadId = cursor.getString(0);
			cursor.close();
			return threadId;
		}else{
			cursor.close();
			return threadId;
		}
	}







	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(1000 == resultCode){
			(new AlertDialog.Builder (this)).setTitle("提示").setMessage("新增任务保存成功").setPositiveButton("确定", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
				}
			}).show();
		}
		if(1008 == requestCode){
			init();
		}
		else if(CONTACT_ADD_EDIT_REQUST_CODE == requestCode){
		    if(resultCode != 3 && resultCode != 4){
		        return;
		    }
		    Bundle bundle = data.getExtras();
            int contactsId = bundle.getInt("contacts_id");
            int sysContactId = bundle.getInt("sys_contactid");
            String name = bundle.getString("name");
            String address = bundle.getString("address");
            String email = bundle.getString("email");
            String company = bundle.getString("company");
            String job = bundle.getString("job");
            String remarks = bundle.getString("remarks");
            String familyPhone = bundle.getString("family_phone");
            String officePhone = bundle.getString("office_phone");
            String mobilePhone = bundle.getString("mobile_phone");
            String sortKey = bundle.getString("sort_key");
            String lookupKey = bundle.getString("lookup_key");
            long phoneId = bundle.getLong("photoid");
		    if(resultCode == 4){
	            for(ContactBean cb : list){
	                if(cb.getContactId() == sysContactId){
	                    cb.setDisplayName(name);
	                    cb.setPhoneNum(mobilePhone);
	                    cb.setSortKey(sortKey);
	                    break;
	                }
	            }
	            
		    }
		    else if(resultCode == 3){
		        ContactBean newCb = new ContactBean();
		        newCb.setContactId(sysContactId);
		        newCb.setCustomContactsId(contactsId);
		        newCb.setDisplayName(name);
		        newCb.setSortKey(sortKey);
		        newCb.setLookUpKey(lookupKey);
		        newCb.setPhoneNum(mobilePhone);
		        newCb.setPhotoId(phoneId);
		        list.add(newCb);
		    }
		    ContactComparetor comparetor = new ContactComparetor();
            Collections.sort(list, comparetor);
            adapter.notifyDataSetChanged();
		    
		}
		else if(TASK_ADD_REQUEST_CODE == requestCode){
		    
		}
		
		super.onActivityResult(requestCode, resultCode, data);
	}

	protected void onDestroy() {
		super.onDestroy();
		stopReceiver1();
		if(manager != null){
		    manager.close();
		}
		
	}

	private String ACTION1 = "SET_DEFAULT_SIG";
	private HomeContactActivity.BaseReceiver1 receiver1 = null;
	/**
	 * 打开接收器
	 */
	private void startReceiver1() {
		if(null==receiver1){
			IntentFilter localIntentFilter = new IntentFilter(ACTION1);
			receiver1 = new HomeContactActivity.BaseReceiver1();
			this.registerReceiver(receiver1, localIntentFilter);
		}
	}
	/**
	 * 关闭接收器
	 */
	private void stopReceiver1() {
		if (null != receiver1)
			unregisterReceiver(receiver1);
	}
	public class BaseReceiver1 extends BroadcastReceiver {
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(ACTION1)) {

				String str_bean = intent.getStringExtra("groupbean");
				Gson gson = new Gson();
				GroupBean gb = gson.fromJson(str_bean, GroupBean.class);
				if(gb.getId() == 0){

					init();
				}else{

					queryGroupMember(gb);
				}
			}
		}
	}


   



}
